package com.bbs.util;

//拦截器,用于拦截所有请求实现登录验证+刷新
//TODO: 考虑将token相关的逻辑抽取到单独的工具类中
//TODO: 考虑添加token黑名单机制，用于处理用户主动登出
//TODO: 考虑添加token自动续期机制

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.bbs.dto.UserDTO;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.bbs.util.constant.LOGIN_TOKEN_NAME;
import static com.bbs.util.constant.LOGIN_USER_TTL;

@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //TODO: 考虑将token验证逻辑抽取到单独的方法中
        //TODO: 考虑添加请求路径日志记录
        //TODO: 考虑添加token格式验证
        
        //获取请求头的token
        String token = request.getHeader(LOGIN_TOKEN_NAME);
        
        //token为空，返回未登录错误
        if(StrUtil.isBlank(token)){
//            log.info("拦截器拦截成功,请求信息:{}",request.getPathInfo());
//            response.setContentType("application/json;charset=UTF-8");
//            response.setCharacterEncoding("UTF-8");
//            response.getWriter().write("{\"success\":false,\"errorMsg\":\"未登录或登录已过期\",\"data\":null,\"total\":null}");
            log.info("拦截器逻辑未修改");
        }

        //TODO: 考虑添加token格式验证
        //TODO: 考虑添加token黑名单检查
        
        //根据token从Redis中获取用户信息
        else{
            Map<Object,Object> map = stringRedisTemplate.opsForHash().entries(token);

            //用户信息不存在，返回未登录错误
            if(map.isEmpty()){
                response.setContentType("application/json;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("{\"success\":false,\"errorMsg\":\"未登录或登录已过期\",\"data\":null,\"total\":null}");
                return false;
            }
            //TODO: 考虑添加用户信息完整性验证
            //将Redis中的用户信息转换为UserDTO对象
            UserDTO userDTO = BeanUtil.fillBeanWithMap(map, new UserDTO(), false);
            //将用户信息保存到ThreadLocal中，方便后续使用
            UserHolder.saveUser(userDTO);
            //刷新token的过期时间
            //TODO: 考虑将刷新时间配置化
           // stringRedisTemplate.expire(token, LOGIN_USER_TTL, TimeUnit.DAYS);//TODO暂时注释
        }


        return true;
    }
}
